package com.ywx.yypicturebackend.api.aliyunai;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ywx.yypicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.ywx.yypicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.ywx.yypicturebackend.api.aliyunai.model.GetOutPaintingTaskResponseResult;
import com.ywx.yypicturebackend.exception.BusinessException;
import com.ywx.yypicturebackend.exception.ErrorCode;
import com.ywx.yypicturebackend.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class AliyunAiService {

    @Value("${aliyunAi.apiKey}")
    private String apiKey;

    private static final String createOutPaintingTaskUrl = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";
    private static final String getOutPaintingTaskResultUrl = "https://dashscope.aliyuncs.com/api/v1/tasks/";


    /**
     * 创建ai扩图任务
     * @param request
     * @return
     */
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreateOutPaintingTaskRequest request) {
        HttpRequest httpRequest = HttpUtil.createRequest(Method.POST, createOutPaintingTaskUrl);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Bearer " + apiKey);
        headers.put("X-DashScope-Async", "enable");//必须要开启异步处理
        httpRequest.addHeaders(headers);

        httpRequest.body(JSONUtil.toJsonStr(request));

        //保证资源会被释放
        try (HttpResponse execute = httpRequest.execute()) {

            if (execute.getStatus() != 200) {
                log.error("Ai扩图接口调用失败：{}", execute.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "Ai扩图失败");

            }


            String responseBody = execute.body();
            // 解析响应对象
            CreateOutPaintingTaskResponse createOutPaintingTaskResponse = JSONUtil.toBean(responseBody, CreateOutPaintingTaskResponse.class);
            ThrowUtils.throwIf(createOutPaintingTaskResponse == null, new BusinessException(ErrorCode.OPERATION_ERROR, "Ai扩图失败"));


            String code = createOutPaintingTaskResponse.getCode();
            if (code!=null){
                log.error("Ai扩图接口调用失败：{}", responseBody);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "Ai扩图失败:" + createOutPaintingTaskResponse.getMessage());
            }

            return createOutPaintingTaskResponse;
        }


    }


    /**
     * 查询ai扩图任务执行情况
     * @param taskId
     * @return
     */
    public GetOutPaintingTaskResponseResult getOutPaintingTaskResult(String taskId) {
        HttpRequest httpRequest = HttpUtil.createRequest(Method.GET, getOutPaintingTaskResultUrl + taskId);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Bearer " + apiKey);
        httpRequest.addHeaders(headers);

        HttpResponse execute = httpRequest.execute();
        ThrowUtils.throwIf(execute.getStatus() != 200, new BusinessException(ErrorCode.OPERATION_ERROR, "获取ai扩图任务结果失败!"));

        String responseBody = execute.body();

        GetOutPaintingTaskResponseResult getOutPaintingTaskResponseResult = JSONUtil.toBean(responseBody, GetOutPaintingTaskResponseResult.class);


        return getOutPaintingTaskResponseResult;
    }


}
